<template>
  <div>
    <ButtonGroup
      :options="buttons"
      class="button-container"
      @click="handleButtonClick"
    />
    <p-table
      class="table-container"
      :custom-header-row="customHeaderRowMinxin"
      row-key="id"
      :columns="columns"
      bordered
      :scroll="{ x: '100%', y: 'calc(100vh - 395px)' }"
      :pagination="paginationMixin"
      :data-source="dataSource"
      :row-selection="rowSelectionMixin"
      @change="handleTableChange"
    >
      <template slot="parentName" slot-scope="text, record">
        <span v-if="!(record.id + '').includes('dai')">{{ text }}</span>
        <Selectleseleave
          v-else
          v-model="record.parentId"
          state="1"
          :has-all="false"
        />
      </template>
      <template slot="loseName" slot-scope="text, record">
        <span v-if="!(record.id + '').includes('dai')">{{ text }}</span>
        <p-input v-else v-model="record.loseName" placeholder="请输入" />
      </template>
      <template slot="state" slot-scope="text, record">
        <p-select v-model="record.state" style="width: 5vw">
          <p-select-option :key="1" :value="1">有效</p-select-option>
          <p-select-option :key="0" :value="0">失效</p-select-option>
        </p-select>
      </template>
    </p-table>
  </div>
</template>

<script>
import mixinTable from '@/mixins/mixin-table.js';
import { postLoseList, postLoseDelete, postLoseInsert } from '@/api/lose.js';
import Selectleseleave from '@/components/select/Selectleseleave.vue';
let index = 0;
const createDefaultItem = () => ({
  id: 'dai' + index++,
  loseName: '',
  state: 1,
  parentId: '',
  createUserName: '',
  createTime: '',
  updateUserName: '',
  updateTime: '',
});
export default {
  components: {
    Selectleseleave,
  },
  mixins: [mixinTable],
  props: {
    buttons: {
      type: [Array],
      default: () => [
        {
          key: 'add',
          type: 'primary',
          label: '新增',
        },
        {
          key: 'save',
          label: '保存',
        },
        {
          key: 'delete',
          label: '删除',
          icon: 'delete',
        },
      ],
    },
  },
  data() {
    return {};
  },
  computed: {
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '失销类别',
          dataIndex: 'parentName',
          width: 200,
          required: true,
          scopedSlots: { customRender: 'parentName' },
        },
        {
          align: 'center',
          title: '失销细类',
          dataIndex: 'loseName',
          width: 200,
          required: true,
          scopedSlots: { customRender: 'loseName' },
        },
        {
          align: 'center',
          title: '状态',
          dataIndex: 'state',
          width: 100,
          required: true,
          scopedSlots: { customRender: 'state' },
        },
        {
          align: 'center',
          title: '创建人',
          dataIndex: 'createUserName',
          width: 100,
        },
        {
          align: 'center',
          title: '创建时间',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          align: 'center',
          title: '最后修改人',
          dataIndex: 'updateUserName',
          width: 100,
        },
        {
          align: 'center',
          title: '最后修改时间',
          dataIndex: 'updateTime',
          width: 200,
        },
      ];
      return columns;
    },
  },
  watch: {},
  created() {
    this.getList();
  },

  methods: {
    async getList(val) {
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
      };
      const res = await postLoseList({
        ...page,
        leseLevel: '2',
        status: '1',
      });
      if (val) {
        const filters = this.dataSource.filter(item => {
          return (item.id + '').includes('dai');
        });
        const data = res.data.data?.records || [];
        this.dataSource = [...data, ...filters];
        this.paginationMixin.total = res.data.data?.total + filters.length - 1;
      } else {
        this.dataSource = res.data.data?.records || [];
        this.paginationMixin.total = res.data.data?.total;
      }
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    addCallback() {
      this.dataSource.push({ ...createDefaultItem() });
      this.paginationMixin.total += 1;
    },
    async saveCallback() {
      const list = this.dataSource;
      const loseReasonCfg = list.map(item => {
        return {
          loseName: item.loseName,
          state: item.state,
          parentId: item.parentId,
          leseLevel: '2',
          id: (item.id + '').includes('dai') ? undefined : item.id,
        };
      });
      const addList = list
        .filter(item => item.loseName.trim() === '')
        .map(item => {
          return {
            loseName: item.loseName,
          };
        });
      if (addList.length) {
        this.$message.error('失销原因类别不能为空');
        return;
      }
      await postLoseInsert(loseReasonCfg);
      this.$message.success('保存成功');
      this.getList();
    },
    deleteCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys;
      if (!ids.length) {
        this.$message.error('请先选择数据！');
        return;
      }
      const idList = ids
        .filter(item => !(item + '').includes('dai'))
        .map(item => {
          return item;
        });
      this.$confirm(`该操作将删除 ${ids.length} 条数据，是否确认？`)
        .then(async () => {
          ids.forEach(id => {
            if ((id + '').includes('dai')) {
              const index = this.dataSource.findIndex(item => item.id === id);
              this.dataSource.splice(index, 1);
            }
          });
          this.rowSelectionMixin.selectedRowKeys = [];
          if (idList.length) {
            await postLoseDelete(idList);
          }
          this.$message.success('删除成功');
          this.getList(true);
        })
        .catch(() => {
          // console.log('e: ', e);
        });
      // this.getList();
    },
    handleInputChange(e, text, record, index, key) {
      this.dataSource[index][key] = e;
    },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.getList(true);
    },
  },
};
</script>

<style lang="less" scoped>
.item-container {
  display: flex;
  align-items: center;
}
.button-container {
  margin-bottom: 20px;
}
.table-container {
  margin-bottom: 40px;
}

/deep/ .poros-select-selection {
  border: none;
}
</style>
